package com.github.com.tools;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DateTool {

	private static final SimpleDateFormat year = new SimpleDateFormat("yyyy");
	private static final SimpleDateFormat month = new SimpleDateFormat("yyyyMM");
	private static final SimpleDateFormat today = new SimpleDateFormat("yyyyMMdd");
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	private static final SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
	private static final SimpleDateFormat hmsFormat = new SimpleDateFormat("HHmmss");
	
	private static final SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static final SimpleDateFormat datetimeSFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
	private static final SimpleDateFormat datetimeSSFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
	private static final SimpleDateFormat datetimeSSSFormat = new SimpleDateFormat("yyyyMMddHHmmss");
	private static final SimpleDateFormat datetimeSSS = new SimpleDateFormat("yyyyMMddHHmm");
	private static final SimpleDateFormat dateStrFormat = new SimpleDateFormat("yyMMddHHmmssSSS");
	private static final SimpleDateFormat datetimes = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
	

	/**
	 * 获得当前时间的<code>java.util.Date</code>对象
	 */
	public static Date now() {
		return new Date();
	}
	/**
	 * 获得当前日期时间：yyyyMM
	 */
	public static String months() {
		return month.format(now());
	}
	/**
	 * 获得当前日期时间：yyyy-MM-dd HH:mm:ss
	 */
	public static String currentDatetime() {
		return datetimeFormat.format(now());
	}
	/**
	 * 获得当前日期时间：yyyyMMdd HH:mm:ss
	 */
	public static String currentTimes() {
		return datetimes.format(now());
	}
	/**
	 * 获得当前日期时间：yyyy/MM/dd HH:mm
	 */
	public static String currentDatetimeSS() {
		return datetimeSSFormat.format(now());
	}
	/**
	 * 获得当前日期时间：yyyyMMddHHmmss
	 */
	public static String currentDatetimeSSS() {
		return datetimeSSSFormat.format(now());
	}
	
	/**
	 * 获得当前日期时间：yyyyMMddHHmm
	 */
	public static String currentDatetimeMo() {
		return datetimeSSS.format(now());
	}
	
	/**
	 * 获得当前日期：yyyyMMdd
	 */
	public static String today() {
		return today.format(now());
	}
	/**
	 * 获得当前年份 ：yyyy
	 */
	public static String year() {
		return year.format(now());
	}
	/**
	 * 获得下一日期 ：yyyyMMdd
	 */
	public static String nextDay() {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DAY_OF_MONTH, 1);
		return today.format(c.getTime());
	}
	/**
	 * 获得当前日期时间：yyyy-MM-dd HH:mm:ss:SSS
	 */
	public static String currentDatetimeS() {
		return datetimeSFormat.format(now());
	}
	/**
	 * 格式化日期时间
	 * @param date
	 * @param pattern：格式化模式，详见{@link SimpleDateFormat}构造器
	 */
	public static String formatDatetime(Date date, String pattern) {
		SimpleDateFormat customFormat = (SimpleDateFormat) datetimeFormat.clone();
		customFormat.applyPattern(pattern);
		return customFormat.format(date);
	}
	/**
	 * 获得当前日期：yyyy-MM-dd
	 */
	public static String currentDate() {
		return dateFormat.format(now());
	}
	/**
	 * 格式化日期：yyyy-MM-dd
	 */
	public static String formatDate(Date date) {
		return dateFormat.format(date);
	}
	/**
	 * 获得当前时间：HH:mm:ss
	 */
	public static String currentTime() {
		return timeFormat.format(now());
	}
	/**
	 * 获得当前时间：HHmmss
	 */
	public static String currentTime8() {
		return hmsFormat.format(now());
	}
	/**
	 * 格式化时间：HH:mm:ss
	 */
	public static String formatTime(Date date) {
		return timeFormat.format(date);
	}
	public static Calendar calendar() {
		Calendar cal = GregorianCalendar.getInstance(Locale.CHINESE);
		cal.setFirstDayOfWeek(Calendar.MONDAY);
		return cal;
	}
	/**
	 * 获得当前时间的毫秒数：System#currentTimeMillis()
	 */
	public static long millis() {
		return System.currentTimeMillis();
	}
	/**
	 * 
	 * 获得当前Chinese月份
	 */
	public static int month() {
		return calendar().get(Calendar.MONTH) + 1;
	}

	/**
	 * 获得月份中的第几天
	 */
	public static int dayOfMonth() {
		return calendar().get(Calendar.DAY_OF_MONTH);
	}

	/**
	 * 今天是星期的第几天
	 */
	public static int dayOfWeek() {
		return calendar().get(Calendar.DAY_OF_WEEK);
	}

	/**
	 * 今天是年中的第几天
	 */
	public static int dayOfYear() {
		return calendar().get(Calendar.DAY_OF_YEAR);
	}

	/**
	 *判断原日期是否在目标日期之前
	 * @param src：原日期 
	 * @param dst：目标日期
	 */
	public static boolean isBefore(Date src, Date dst) {
		return src.before(dst);
	}

	/**
	 *判断原日期是否在目标日期之后
	 * @param src：原日期 
	 * @param dst：目标日期
	 */
	public static boolean isAfter(Date src, Date dst) {
		return src.after(dst);
	}

	/**
	 *判断两日期是否相同
	 */
	public static boolean isEqual(Date date1, Date date2) {
		return date1.compareTo(date2) == 0;
	}

	/**
	 * 判断某个日期是否在某个日期范围
	 * @param beginDate：日期范围开始
	 * @param endDate：日期范围结束
	 * @param src：需要判断的日期
	 */
	public static boolean between(Date beginDate, Date endDate, Date src) {
		return beginDate.before(src) && endDate.after(src);
	}

	/**
	 * 获得当前月的最后一天：HH:mm:ss为0，毫秒为999
	 */
	public static Date lastDayOfMonth() {
		Calendar cal = calendar();
		cal.set(Calendar.DAY_OF_MONTH, 0); // M月置零
		cal.set(Calendar.HOUR_OF_DAY, 0);// H置零
		cal.set(Calendar.MINUTE, 0);// m置零
		cal.set(Calendar.SECOND, 0);// s置零
		cal.set(Calendar.MILLISECOND, 0);// S置零
		cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) + 1);// 月份+1
		cal.set(Calendar.MILLISECOND, -1);// 毫秒-1
		return cal.getTime();
	}

	/**
	 * 获得当前月的第一天
	 */
	public static Date firstDayOfMonth() {
		Calendar cal = calendar();
		cal.set(Calendar.DAY_OF_MONTH, 1); // M月置1
		cal.set(Calendar.HOUR_OF_DAY, 0);// H置零
		cal.set(Calendar.MINUTE, 0);// m置零
		cal.set(Calendar.SECOND, 0);// s置零
		cal.set(Calendar.MILLISECOND, 0);// S置零
		return cal.getTime();
	}

	private static Date weekDay(int week) {
		Calendar cal = calendar();
		cal.set(Calendar.DAY_OF_WEEK, week);
		return cal.getTime();
	}

	/**
	 * 获得周五日期
	 * 注：日历工厂方法{@link #calendar()}设置类每个星期的第一天为Monday，US等每星期第一天为sunday
	 */
	public static Date friday() {
		return weekDay(Calendar.FRIDAY);
	}

	/**
	 * 获得周六日期
	 * 注：日历工厂方法{@link #calendar()}设置类每个星期的第一天为Monday，US等每星期第一天为sunday
	 */
	public static Date saturday() {
		return weekDay(Calendar.SATURDAY);
	}

	/**
	 * 获得周日日期
	 * 注：日历工厂方法{@link #calendar()}设置类每个星期的第一天为Monday，US等每星期第一天为sunday
	 */
	public static Date sunday() {
		return weekDay(Calendar.SUNDAY);
	}

	/**
	 * 将字符串日期时间转换成java.util.Date类型
	 * 日期时间格式yyyy-MM-dd HH:mm:ss
	 * @param datetime
	 */
	public static Date parseDatetime(String datetime) throws ParseException {
		return datetimeFormat.parse(datetime);
	}

	/**
	 * 将字符串日期转换成java.util.Date类型
	 * 日期时间格式yyyy-MM-dd
	 * @param date
	 */
	public static Date parseDate(String date) throws ParseException {
		return dateFormat.parse(date);
	}
	
	/**
	 * 将字符串日期转换成java.util.Date类型
	 * 日期时间格式yyyyMMdd
	 * @param date
	 */
	public static Date parseDates(String date) throws ParseException {
		return today.parse(date);
	}
	

	/**
	 * 将字符串日期转换成java.util.Date类型
	 * 时间格式 HH:mm:ss
	 * @param time
	 */
	public static Date parseTime(String time) throws ParseException {
		return timeFormat.parse(time);
	}

	/**
	 * 根据自定义pattern将字符串日期转换成java.util.Date类型
	 * @param datetime
	 * @param pattern
	 */
	public static Date parseDatetime(String datetime, String pattern)
			throws ParseException {
		SimpleDateFormat format = (SimpleDateFormat) datetimeFormat.clone();
		format.applyPattern(pattern);
		return format.parse(datetime);
	}
	
	/**
     * 小时:分钟的正则表达式检查<br>
     * @param time：要检查的字符串
     * @return boolean：返回检查结果
     */
    public static boolean isShortTime (String time) {
        if(time == null){
            return false;
        }
        String regEx = " ^([0-1]{1}/d|2[0-3]):([0-5]/d)$";
        Pattern p = Pattern.compile(regEx);
        Matcher matcher = p.matcher(time);
        return matcher.matches();
    }
    
    public static String currentDate8() {
		return today.format(now());
	}
	
	public static boolean isEqualsDate(String date){
		if(currentDate8().equals(date)){
			return true;
		}
		return false;
	}
	/**
	 * 获得当前天数
	 * 日期时间格式yyyyMMdd
	 */
	public static Integer currentDay() {
		Calendar a = Calendar.getInstance();
		return a.get(Calendar.DATE);
	}
	/**
	 * 比较两个日期的大小：yyyyMMdd HH:mm:ss
	 * date1 >= date2   false 
	 * date1 < date2    true
	 */
	public static boolean compareDateTime(String date1, String date2) {
        DateFormat df = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
        try {
            Date dt1 = df.parse(date1);
            Date dt2 = df.parse(date2);
            if (dt1.getTime() >= dt2.getTime()) {
                return false;
            } else if (dt1.getTime() < dt2.getTime()) {
                return true;
            } 
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return false;
    }
	/**
	 * 比较两个日期的大小：yyyyMMdd
	 * date1 >= date2   false 
	 * date1 < date2    true
	 */
	public static boolean compareDate(String date1, String date2) {
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        try {
            Date dt1 = df.parse(date1);
            Date dt2 = df.parse(date2);
            if (dt1.getTime() >= dt2.getTime()) {
                //System.out.println("dt1 在 dt2前 dt1 > dt2");
                return false;
            } else if (dt1.getTime() < dt2.getTime()) {
                //System.out.println("dt1在dt2后 dt1 < dt2");
                return true;
            } 
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return false;
    }
	/**
	 * 比较两个日期的大小：yyyyMMdd
	 * date1 > date2   false 
	 * date1 <= date2    true
	 */
	public static boolean compareDates(String date1, String date2) {
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        try {
            Date dt1 = df.parse(date1);
            Date dt2 = df.parse(date2);
            if (dt1.getTime() > dt2.getTime()) {
                //System.out.println("dt1 在 dt2前 dt1 > dt2");
                return false;
            } else if (dt1.getTime() <= dt2.getTime()) {
                //System.out.println("dt1在dt2后 dt1 < dt2");
                return true;
            } 
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return false;
    }
	/**
	 * 比较两个时间的大小：HH:mm
	 * time1 >= time2   false 
	 * time1 < time2    true
	 */
	public static boolean compareTime(String time1, String time2) {
        DateFormat df = new SimpleDateFormat("HH:mm");
        try {
            Date dt1 = df.parse(time1);
            Date dt2 = df.parse(time2);
            if (dt1.getTime() >= dt2.getTime()) {
                //System.out.println("dt1 在 dt2前 dt1 > dt2");
                return false;
            } else if (dt1.getTime() < dt2.getTime()) {
                //System.out.println("dt1在dt2后 dt1 < dt2");
                return true;
            } 
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return false;
    }
	/**
	 * 返回两个日期间隔天数
	 * @param startDate
	 * @param endDate
	 */
	public static int loadDate(String startDate,String endDate){
        int days = 0;
		try {
            //时间转换类
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Date date1 = sdf.parse(startDate);
            Date date2 = sdf.parse(endDate);
            //将转换的两个时间对象转换成Calendard对象
            Calendar can1 = Calendar.getInstance();
            can1.setTime(date1);
            Calendar can2 = Calendar.getInstance();
            can2.setTime(date2);
            //拿出两个年份
            int year1 = can1.get(Calendar.YEAR);
            int year2 = can2.get(Calendar.YEAR);
            //天数
            Calendar can = null;
            //减去小的时间在这一年已经过了的天数
            //加上大的时间已过的天数
            if(can1.before(can2)){
                days -= can1.get(Calendar.DAY_OF_YEAR);
                days += can2.get(Calendar.DAY_OF_YEAR);
                can = can1;
            }else{
                days -= can2.get(Calendar.DAY_OF_YEAR);
                days += can1.get(Calendar.DAY_OF_YEAR);
                can = can2;
            }
            for (int i = 0; i < Math.abs(year2-year1); i++) {
                //获取小的时间当前年的总天数
                days += can.getActualMaximum(Calendar.DAY_OF_YEAR);
                //再计算下一年。
                can.add(Calendar.YEAR, 1);
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
		days = days + 1;
        return days;
	}
	/**
	 * 获取指定日期之前/之后的指定几日的日期
	 * @param day-指定日期,before-前(true)/后(false),num-指定日
	 */
	public static String queryPriDateForDay(String day,boolean before,int num){
	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		try{
	        Calendar calendar = Calendar.getInstance();
	        calendar.set(Integer.valueOf(day.substring(0, 4)), Integer.valueOf(day.substring(4, 6))-1, Integer.valueOf(day.substring(6, day.length())));
	        if(before){
	        	calendar.add(Calendar.DATE, -num);
	        }else{
	        	calendar.add(Calendar.DATE, num);
	        }
	        Date date1 = calendar.getTime();
	        return sdf.format(date1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	/**
	 * 获取指定 格式的当前日期
	 * @param formart-指定格式,如“yyyyMMdd”
	 */
	public static String queryNowDay(String formart){
		String d="";
		try{
			Date date= new Date();
			SimpleDateFormat df = new SimpleDateFormat(formart);
			d=df.format(date);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return d;
	}
	/**
	 * 将GregorianCalendar对象转换为日期字符串
	 * 说明：本方法的参数需要使用parse2Cal方法转换,如果参数是实例化的对象,实例化时月份的范围是0-11,推荐使用Calendar类定义的月份常量
	 * @param greCalendar 日期对象
	 */
	@SuppressWarnings("static-access")
	public static String parse2Str(GregorianCalendar greCalendar) {
		String year = String.valueOf(greCalendar.get(greCalendar.YEAR));
		String month = String.valueOf(greCalendar.get(greCalendar.MONTH) + 1);
		String day = String.valueOf(greCalendar.get(greCalendar.DAY_OF_MONTH));
		if (month.length() == 1) {
			month = "0" + month;
		}
		if (day.length() == 1) {
			day = "0" + day;
		}
		return year + month + day;
	}
	/**
	 * 获取指定日期月份的最后一天，如果日期格式不正确或为空，返回当前月份的最后一天
	 * @author 顾楠 建立文件日期 2008-10-30
	 * @param date
	 */
	@SuppressWarnings("static-access")
	public static String queryLastDayOfMonth(String date) {
		GregorianCalendar calendar = null;
		if (date != null && date.trim().length() == 8) {
			calendar = parse2Cal(date);
		} else {
			calendar = new GregorianCalendar();
		}
		calendar.set(calendar.DATE, 1);
    	calendar.roll(calendar.DATE, -1);
    	return calendar.get(Calendar.DATE) + "";
	}
	
	/**
	 * 将日期字符串转换为GregorianCalendar对象
	 * @param dateStr 日期字符串
	 */
	public static GregorianCalendar parse2Cal(String dateStr) {
    	int year = Integer.parseInt(dateStr.substring(0, 4));
    	//月份从0开始
    	int month = Integer.parseInt(dateStr.substring(4, 6)) - 1;
    	int dayOfMonth = Integer.parseInt(dateStr.substring(6, 8));
        return new GregorianCalendar(year, month, dayOfMonth);
	}
	
	/**
	 * 根据周几获取日期
	 * @param date
	 */
	public static String queryDateForWeekDay(String date,String weekDay) {
		String weekTmp =dateToWeek(date);	
		try {
			if(weekDay.equals(weekTmp)){
				return queryPriDateForDay(date,false,7);
			}else if(Integer.valueOf(weekTmp)>Integer.valueOf(weekDay)){
				return queryPriDateForDay(date,false,7-Integer.valueOf(weekTmp)+Integer.valueOf(weekDay));
			}else{
				return queryPriDateForDay(date,false,Integer.valueOf(weekDay)-Integer.valueOf(weekTmp));
			}
		}catch (Exception e) {
			e.printStackTrace();
			return date;
		}
		
	}
	/**
     * 日期转星期
     * @param datetime
     */
    public static String dateToWeek(String date) {
        SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
        String[] weekDays = { "7", "1", "2", "3", "4", "5", "6" };
        Calendar cal = Calendar.getInstance(); // 获得一个日历
        Date datet = null;
        try {
            datet = f.parse(date);
            cal.setTime(datet);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
        if (w < 0){
        	w = 0;
        }
        return weekDays[w];
    }
    /**
	 * 获取指定日期之前/之后的指定几月的日期
	 * @param day-指定日期,before-前(true)/后(false),num-指定日
	 */
	public static String queryPriDateForMoth(String day,boolean before,int num){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		try{
	        Calendar calendar = Calendar.getInstance();
	        calendar.set(Integer.valueOf(day.substring(0, 4)), Integer.valueOf(day.substring(4, 6))-1, Integer.valueOf(day.substring(6, day.length())));
	        if(before){
	        	calendar.add(Calendar.MONTH, -num);
	        }else{
	        	calendar.add(Calendar.MONTH, num);
	        }
	        Date date1 = calendar.getTime();
	        return sdf.format(date1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	/**
	 * 获取指定日期之前/之后的指定几月的日期
	 * @param day-指定日期,before-前(true)/后(false),num-指定日
	 */
	public static String queryPriMoth(String date){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
		try{
	        Calendar calendar = Calendar.getInstance();
	        calendar.set(Integer.valueOf(date.substring(0, 4)), Integer.valueOf(date.substring(4, 6))-1, Integer.valueOf(date.substring(6, date.length())));
	        calendar.add(Calendar.MONTH, -1);
	        Date date1 = calendar.getTime();
	        return sdf.format(date1);
		} catch (Exception e) {
			e.printStackTrace();
			e.printStackTrace();
		}
		return "";
	}
	/**
	 * 将日期转换为指定的格式
	 * @param pattern
	 * @param date
	 */
	public static String dateFormat(String pattern, Date date) {
		SimpleDateFormat sf = new SimpleDateFormat(pattern);
		return sf.format(date);
	}
	/**
	 * 将String类型的日期转换成Date类型
	 * @param sDate
	 * @param pattern
	 */
	public static Date StringformatDate(String sDate, String pattern) {
		Date date = null;
		SimpleDateFormat format = new SimpleDateFormat(pattern);
		try {
			date = format.parse(sDate);
		} catch (ParseException e) {
			return null;
		}
		return date;
	}
	/** 
	* 获得指定日期的前n天 
	* @param specifiedDay 
	*/ 
	public static String getDayBefore(String specifiedDay,int n) {
		Calendar c = Calendar.getInstance();
		Date date = null;
		try {
			date = new SimpleDateFormat("yyyyMMdd").parse(specifiedDay);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		c.setTime(date);
		int day = c.get(Calendar.DATE);
		c.set(Calendar.DATE, day + n);
		String dayBefore = new SimpleDateFormat("yyyyMMdd").format(c.getTime());
		return dayBefore;
	}
	
	/**
     * date2比date1多的天数
     * @param date1    
     * @param date2
     */
	public static int differentDays(String dateStr, String dateStr2) {
		try {
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
			Date date2 = format.parse(dateStr2);
			Date date1 = format.parse(dateStr);
			Calendar cal1 = Calendar.getInstance();
			cal1.setTime(date1);
			Calendar cal2 = Calendar.getInstance();
			cal2.setTime(date2);
			int day1 = cal1.get(Calendar.DAY_OF_YEAR);
			int day2 = cal2.get(Calendar.DAY_OF_YEAR);
			int year1 = cal1.get(Calendar.YEAR);
			int year2 = cal2.get(Calendar.YEAR);
			 // 同一年
			if (year1 != year2){
				int timeDistance = 0;
				for (int i = year1; i < year2; i++) {
					// 闰年
					if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
						timeDistance += 366;
					} else {
						// 不是闰年
						timeDistance += 365;
					}
				}
				return timeDistance + (day2 - day1);
			} else {
				// 不同年
				System.out.println("判断day2 - day1 : " + (day2 - day1));
				return day2 - day1;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
	}
    /**
	 * 获得当前日期 (日期时间格式yyyyMMdd)
	 */
	public static String dateStr() {
		return dateStrFormat.format(now()) + (int)((Math.random()*9+1)*10000);
	}
    /** 
     * 获得指定日期的前一天 
     * @param specifiedDay 
     */  
    public static String getSpecifiedDayBefore(String specifiedDay) {//可以用new Date().toLocalString()传递参数  
        Calendar c = Calendar.getInstance();  
        Date date = null;  
        try {  
            date = new SimpleDateFormat("yyyyMMdd").parse(specifiedDay);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        c.setTime(date);  
        int day = c.get(Calendar.DATE);  
        c.set(Calendar.DATE, day - 1);  
        String dayBefore = new SimpleDateFormat("yyyyMMdd").format(c.getTime());  
        return dayBefore;  
    }  
    
    public static List<String> dateSplit(String sdate1, String sdate2) throws Exception {
	    List<String> dateList = new ArrayList<String>();
		try {
	        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
	        Date startDate = sdf.parse(sdate1);
	        Date endDate = sdf.parse(sdate2);
	        List<Date> lists = dateSplit(startDate, endDate);
	        if (!lists.isEmpty()) {
	            for (Date date : lists) {
	            	String end = sdf.format(date);
	            	if(!end.equals(sdate2)){
		                dateList.add(end);
	            	}
	            }
	        }
	    } catch (Exception e) {
            e.printStackTrace(); 
	    }
	    return dateList;
	}
    
    private static List<Date> dateSplit(Date startDate, Date endDate) throws Exception {
	    if (!startDate.before(endDate)){
	        throw new Exception("开始时间应该在结束时间之后");
	    }
	    Long spi = endDate.getTime() - startDate.getTime();
	    Long step = spi / (24 * 60 * 60 * 1000);// 相隔天数
	    List<Date> dateList = new ArrayList<Date>();
	    dateList.add(endDate);
	    for (int i = 1; i <= step; i++) {
	        dateList.add(new Date(dateList.get(i - 1).getTime() - (24 * 60 * 60 * 1000)));// 比上一天减一
	    }
	    return dateList;
	}
	
    /**
     * 查询两个日期之前的所有日期集合
     * @param startDate 起始日期
     * @param endDate
     * @param b1 = true：包含起始日期
     * @param b2 = true：包含截止日期
     */
    public static List<String> dateList(String startDate, String endDate,boolean b1,boolean b2) throws Exception {
	    List<String> dateList = new ArrayList<String>();
		try {
			if(b1){
				dateList.add(startDate);
			}
			while(Integer.valueOf(startDate) < Integer.valueOf(endDate)){
				startDate = DateTool.getDayBefore(startDate, 1);
				if(endDate.equals(startDate)){
					if(b2){
						dateList.add(endDate);
					}
				}else{
					dateList.add(startDate);
				}
			}
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
	    return dateList;
	}
    
    /**
	 * 返回两个日期相差的天数
	 * @param pFormer 较早的日期
	 * @param pLatter 较晚的日期
	 */
	public static int daysBetween(GregorianCalendar pFormer, GregorianCalendar pLatter){
        GregorianCalendar vFormer = pFormer, vLatter = pLatter;
        if (pFormer.before(pLatter)) {
            vFormer = pFormer;
            vLatter = pLatter;
        } else {
            vFormer = pLatter;
            vLatter = pFormer;
        }
        vFormer.set(Calendar.MILLISECOND, 0);
        vFormer.set(Calendar.SECOND, 0);
        vFormer.set(Calendar.MINUTE, 0);
        vFormer.set(Calendar.HOUR_OF_DAY, 0);
        vLatter.set(Calendar.MILLISECOND, 0);
        vLatter.set(Calendar.SECOND, 0);
        vLatter.set(Calendar.MINUTE, 0);
        vLatter.set(Calendar.HOUR_OF_DAY, 0);
        int counter = 0;
        while (vFormer.before(vLatter)) {
            vFormer.add(Calendar.DATE, 1);
            counter++;
        }
        return counter;
    }
	
	/**
	 * 返回两个日期相差的天数
	 * @param formerStr 较早日期
	 * @param latterStr 较晚日期
	 */
	public static int daysBetween(String formerStr, String latterStr){
        GregorianCalendar former = parse2Cal(formerStr);
        GregorianCalendar latter = parse2Cal(latterStr);
        return daysBetween(former, latter);
    }
	 
	/**
	 * 判断参数的格式是否为“yyyyMMdd”格式的合法日期字符串
	 * @param str
	 */
	public static boolean isValidDate(String str) {
        boolean convertSuccess = true;// 指定日期格式为四位年/两位月份/两位日期，注意yyyy/MM/dd区分大小写；
        if(str.length() != 8){
        	return convertSuccess = false;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        try {// 设置lenient为false.否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
            format.setLenient(false);
            format.parse(str);
        } catch (ParseException e) { // e.printStackTrace();
            // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
            convertSuccess = false;
        }
        return convertSuccess;
    }
	
	/** 
     * 两个时间相差距离多少天多少小时多少分多少秒 
     * @param str1 时间参数 1 格式：1990-01-01 12:00:00 
     * @param str2 时间参数 2 格式：2009-01-01 12:00:00 
     * @return long[] 返回值为：{天, 时, 分, 秒} 
     */  
    public static long[] getDistanceTimes(String starttime, String endtime) {  
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        Date one;  
        Date two;  
        long day = 0;  
        long hour = 0;  
        long min = 0;  
        long sec = 0;  
        try {  
            one = df.parse(starttime);  
            two = df.parse(endtime);  
            long time1 = one.getTime();  
            long time2 = two.getTime();  
            long diff ;  
            if(time1<time2) {  
                diff = time2 - time1;  
            } else {  
                diff = time1 - time2;  
            }  
            day = diff / (24 * 60 * 60 * 1000);  
            hour = (diff / (60 * 60 * 1000) - day * 24);  
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);  
            sec = (diff/1000-day*24*60*60-hour*60*60-min*60);  
        } catch (ParseException e) {  
            e.printStackTrace();  
        }  
        long[] times = {day, hour, min, sec};  
        return times;  
    }  
    
    /** 
     * 两个时间相差距离多少天多少小时多少分多少秒 
     * @param str1 时间参数 1 格式：1990-01-01 12:00:00 
     * @param str2 时间参数 2 格式：2009-01-01 12:00:00 
     * @return String 返回值为：xx天xx小时xx分xx秒 
     */  
    public static String getDistanceTime(String starttime, String endtime) {  
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        Date one;  
        Date two;  
        long day = 0;  
        long hour = 0;  
        long min = 0;  
        long sec = 0;  
        StringBuilder sb = new StringBuilder();
        try {  
            one = df.parse(starttime);  
            two = df.parse(endtime);  
            long time1 = one.getTime();  
            long time2 = two.getTime();  
            long diff ;  
            if(time1<time2) {  
                diff = time2 - time1;  
            } else {  
                diff = time1 - time2;  
            }  
            day = diff / (24 * 60 * 60 * 1000);  
            hour = (diff / (60 * 60 * 1000) - day * 24);  
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);  
            sec = (diff/1000-day*24*60*60-hour*60*60-min*60);  
            if(day > 0){
            	sb.append(day + "天");
            }
            if(hour > 0){
            	sb.append(hour + "小时");
            }
            if(min > 0){
            	sb.append(min + "分");
            }
            if(sec > 0){
            	sb.append(sec + "秒");
            }
        } catch (ParseException e) {  
            e.printStackTrace();  
        }  
        return sb.toString();  
    }
	
    /**
     * 获取月份最大天数
     * @param month
     */
	public static String getMaxDateMonth(String month){
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
			Calendar calendar = Calendar.getInstance();
			Date nowDate = sdf.parse(month);
			calendar = Calendar.getInstance();
			calendar.setTime(nowDate);
			calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
			return today.format(calendar.getTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	/**
	 * 获得当前月份的第N月
	 * @param n
	 */
	public static String calMonth(int n) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.MONTH, n);
		return sdf.format(calendar.getTime());
	}
	/**
	 * 获得当前年份的第N月
	 * @param n
	 */
	public static String calYear(int n) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.YEAR, n);
		return sdf.format(calendar.getTime());
	}
}
